package com.srv.service;

import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.srv.TheException;
import com.srv.model.ID;
import com.srv.model.SummaryUser;
import com.srv.persistence.PersistenceException;
import com.srv.persistence.PersistenceFactory;
import com.srv.util.IDGenerator;

public class IDService extends Service{
	private static Log log = LogFactory.getLog(IDService.class);
	
	/**
	 * 创建一个ID
	 * @param theOwner
	 * @param type
	 * @return
	 * @throws TheException
	 * @see com.srv.model.ID
	 */
	public static String createID(SummaryUser theOwner,int type) throws TheException {
		return createID(theOwner,type,null);
	}
	/**
	 * 创建一个ID
	 * @param theOwner
	 * @param type
	 * @param extend -扩展信息
	 * @return
	 * @throws TheException
	 * @see com.srv.model.ID
	 */
	public static String createID(SummaryUser theOwner,int type,ArrayList<String> extend) throws TheException {		
		String id=IDGenerator.createID();
		ID idObj = new ID();
		idObj.id = id;
		idObj.pid = theOwner.pid;
		idObj.type = type;
		if(extend!=null){
			idObj.extend_1 = extend.get(0);
			if(extend.size()>1){
				idObj.extend_2 = extend.get(1);
			}
		}
		try{
			PersistenceFactory.getIDPersistence().insertID(idObj);
		}catch(PersistenceException pe){
			log.error("save id error"+pe.getMessage());
			throw new TheException("save id Exception");
		}
		return id;
		
	}
	/**
	 * 创建一组ID
	 * @param theOwner
	 * @param counter
	 * @param type
	 * @param extend -扩展信息
	 * @return
	 * @throws TheException
	 * @see com.srv.model.ID
	 */
	public static String[] createIDArray(SummaryUser theOwner,int counter,int type,ArrayList<String> extend) throws TheException {
		String[] ids = new String[counter];
		for(int i=0; i<counter;i++){
			ids[i] = createID(theOwner,type,extend);
		}
		return ids;
	}
	/**
	 * 创建一组ID
	 * @param theOwner
	 * @param counter
	 * @param type
	 * @return
	 * @throws TheException
	 * @see com.srv.model.ID
	 */
	public static String[] createIDArray(SummaryUser theOwner,int counter,int type) throws TheException {
		return createIDArray(theOwner,counter,type,null);
	}
	

	/**
	 * 是否合法的ID.<br/>
	 * 合法的含义：1）格式合法，2）真正被生成过.
	 * @param id
	 * @return
	 * @throws ServiceException
	 */
	public static ID getID(String id) throws TheException{
		//检查格式
		if(!IDGenerator.isValid(id)){ return null;}		
		return PersistenceFactory.getIDPersistence().getID(id);			
				
	}	
}
